cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,      // The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
        
        enemyPrefab : {
            default : null,
            type : cc.Prefab,
        },
        
        // 暂存 Game 对象的引用
        game: {
            default: null,
            serializable: false
        },
        
        // 保存对象
        objs: [],
    },

    // use this for initialization
    onLoad: function () {
        cc.log("enemy manager : onload()");
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {

    },
    
    hello : function () {
        cc.log("enemy manager : hello");
    },
    
    init : function (game) {
        this.game = game;
        
        this.pool = new cc.NodePool('Enemy');
        let initCount = 20;
        for (let i = 0; i < initCount; ++i) {
            let enemy = cc.instantiate(this.enemyPrefab); // 创建节点
            this.pool.put(enemy); // 通过 putInPool 接口放入对象池
        }
        cc.log("enemy manager : enemy manager init()");
    },
    
    create : function () {
        var enemy = null;
        // 使用给定的模板在场景中生成一个新节点
        if (this.pool.size() > 0) {
            enemy = this.pool.get(this); // parentNode will be passed to enemy's reuse method
        } else {
            enemy = cc.instantiate(this.enemyPrefab);
        }
        if (enemy) {
            // 保存对象，以便回收
            this.objs.push(enemy);
            // 设置对象的坐标
            let width = this.node.parent.width;
            let height = this.node.parent.height;
            enemy.getComponent('Enemy').init(this);
            enemy.setPosition(cc.p(cc.randomMinus1To1() * width, height));
            cc.director.getScene().getChildByName('Canvas').addChild(enemy);
        } else {
            cc.error("enemy manager has something wrong");
        }
    },
    
    put : function (enemy) {
        this.pool.put(enemy);
    },

    recoverAll: function () {
        // 遍历对象，回收对象
        for (i in this.objs) {
            this.pool.put(this.objs[i]);
        }
        // 清空缓存对象数组
        this.objs = [];
    },
});
